package com.mr.security.web.webapp.rbac.controller;

import com.mr.security.web.commons.config.SecurityPropertiesConfig;
import com.mr.security.web.commons.utils.ResultVOUtil;
import com.mr.security.web.commons.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Class: UserController
 * User (作者):MRui
 * TODO (描述)：SecurityController(身份认证处理等)
 * Date 2019-01-14 23:55
 */
@Slf4j
@RestController
public class SecurityController {

    //security属性配置
    @Autowired
    private SecurityPropertiesConfig securityProperties;

    //请求缓存类
    private RequestCache requestCache = new HttpSessionRequestCache();
    //spring工具类
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();


    /**
     * User (作者): MRui
     * TODO (描述)：登陆跳转
     * Data：2019-01-19 23:04
     */
    @GetMapping("/toLogin")
    public ModelAndView toLogin() {
        log.info("开始登陆...");
        //跳转到登陆页
        return new ModelAndView("login");
    }
    /**
    * User (作者): MRui
    * TODO (描述)：跳转到主页（spring默认的跳转路径为 "/" ）
    * Data：2019-01-20 21:03
    */
    @GetMapping("/toIndex")
    public ModelAndView toHome() {
        log.info("跳转到主页面...");
        return new ModelAndView("home");
    }

    /**
     * User (作者): MRui
     * TODO (描述)：需要身份认证是跳转到这里
     * Data：2019-01-19 18:10
     */
    @GetMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)//返回401状态码
    public ResultVO requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("开始认证...");
        //拿到引发跳转的请求
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest != null){
            //引发跳转请求的url
            String target = savedRequest.getRedirectUrl();
            log.info("引发跳转的url,target={}",target);
            //判断是否是html(可自定义)结尾的请求（根据实际情况自定义）
            if(StringUtils.endsWithIgnoreCase(target,".html")){
                //跳转到登陆页 url配置到配置文件中，直接配置文件配置即可
                redirectStrategy.sendRedirect(request,response,securityProperties.getLoginPage());
            }else if(StringUtils.endsWithIgnoreCase(target,"logout.do")){
                //security登出方法
                redirectStrategy.sendRedirect(request,response,"logout");
            }
        }
        ResultVO resultVO = ResultVOUtil.error(401,"访问的服务需要身份认证，请引导用户到登陆页！");
        return  resultVO;
    }
}
